<?php

/**
 * Action类
 *
 * @package    lib
 * @subpackage core
 * @author     suning <snsnsky@gmail.com>
 *
 * $Id$
 */

namespace lib\core;

use lib\util\Securimage;
use Passport\User as PUser;

class Action
{
    /**
     * 登录用户ID
     *
     * @var int
     */
    protected $login_uid = 0;

    /**
     * 应用程序类
     *
     * @var Application
     * @access protected
     */
    protected $app;

    /**
     * 构造函数
     *
     * @param Application &$app 应用程序类
     */
    public function __construct(& $app)
    {
        $this->app = $app;
        $this->_initLogin();
    }

    /**
     * 默认Action
     */
    public function doDefault()
    {
        // nothing to do
    }

    /**
     * 统一输出
     *
     * @param mixed $data 输出数据
     * @param string $type 输出类型
     * @param boolean $exit 是否结束程序, true结束, false不结束
     * @param mixed $extra 附加数据
     *
     * @return mixed
     */
    public static function output($data, $type = 'json', $exit = true, $extra = '')
    {
        switch ($type) {
            case 'debug':
                echo '<pre>';
                print_r($data);
                echo '</pre>';
                break;
            case 'xml':
                // echo $this->_toXml();
                break;
            case 'json':
            default:
                if (isset($_GET['callback'])) {
                    if (!headers_sent()) {
                        header("Cache-Control:maxage=1");
                        header("Content-type: text/javascript; charset=UTF-8");
                    }
                    $jsonp = $_GET['callback'];
                    echo $jsonp . '(' . json_encode($data) . ')';
                } else {
                    echo json_encode($data);
                }
        }

        if ($exit) {
            exit();
        }

        return true;
    }

    /**
     * 跨域输出接口
     *
     * @param string $func 回调函数名
     * @param array $data 数据, 建议使用array
     * @param string $domain 请求发起域名
     */
    public static function crossOutput($func, $data, $domain = 'www.qbaoting.com')
    {
        $data = rawurlencode(json_encode($data));
        $time = time();

        if (!preg_match('/[a-z0-9_]+/i', $func)) {
            $func = 'errorfunc';
        }

        if (!preg_match('/[a-z0-9\.]+/i', $domain)) {
            $domain = 'www.qbaoting.com';
        }

        echo "
        <!doctype html>
        <html>
        <head>
        <meta charset=\"utf-8\">
        <title>Crossdomain</title>
        </head>
        <body>
            <iframe src=\"http://{$domain}/proxy.html?callback={$func}&data={$data}&t={$time}\"></iframe>
        </body>
        </html>";

        exit;
    }

    /**
     * 登录判断和检查
     *
     * @param bool /string $redirect         转跳模式.
     *                                             auto: ajax请求返回uid, 反之自动转跳到登录页.
     *                                             true: 强制转跳到登录页
     *                                             false: 始终不转跳, 默认.
     * @return bool/integer                 未登录返回false, 登录返回安全登录UID
     */
    public function isLogin($redirect = false)
    {
        $uid = (int)$_SESSION['UserId'];

        if ($uid < 1) {
            if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && $redirect === 'auto') {
                $redirect = false;
            } else {
                if ($redirect === 'auto') {
                    $redirect = true;
                }
            }

            if ($redirect === true) {
                $referer = rawurlencode("http://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}");
                $this->app->redirect($this->app->cfg['url']['login'] . "?referer={$referer}", 3);
            } else {
                if ($redirect === false) {
                    return false;
                }
            }
        }

        return $uid;
    }

    /**
     * 输出验证输出处理
     */
    public function doCode()
    {
        $options = [
            'image_width' => 96,
            'image_height' => 27,
            'text_scale' => 0.6, //字体比例
        ];
        $img = new Securimage($options);
        $img->show();
    }

    /**
     * 验证验证码是否正确
     *
     * @param string $code
     * @param string $namespace
     * @return boolean
     */
    public function checkCode($code, $namespace = null)
    {
        $img = new Securimage();
        $namespace !== null && $img->namespace = $namespace;
        $chk = $img->check($code);

        return $chk;
    }

    /**
     * 初始化登录状态
     */
    private function _initLogin()
    {
        $user = false;
        $login_uid = $this->isLogin(false);

        if (empty($login_uid) && isset($_COOKIE['_auth'])) {
            $login_uid = cookie_decode($_COOKIE['_auth']);
            if ($login_uid > 0) {
                $user = PUser::getUserInfo($login_uid);
            } else {
                unset($_SESSION['UserId']);
                unset($_SESSION['UserName']);
                setcookie('_auth', '', 1);
                setcookie('_uid', '', 1);
            }
        } else {
            if ($login_uid > 0) {
                $user = PUser::getUserInfo($login_uid);
            }
        }
        // 锁定
        if (!empty($user['UserId']) && $user['Status'] == '0') {
            unset($_SESSION['UserId']);
            unset($_SESSION['UserName']);
            setcookie('_auth', '', 1);
            setcookie('_uid', '', 1);
            $this->app->redirect('http://www.' . CURRENT_HOST . '/');
        } else {
            if ($user['UserId'] > 0) {
                if (empty($_SESSION['UserId'])) {
                    $_SESSION['UserId'] = $user['UserId'];
                    $_SESSION['UserName'] = $user['UserName'];

                    $expire = time() + 31536000;
                    setcookie('_auth', cookie_encode($user['UserId']), $expire);
                    setcookie('_uid', $user['UserId'], $expire);

                    return true;
                }
            }
        }

        return false;
    }

    protected function getRequestHost()
    {
        return $_SERVER['HTTP_HOST'];
    }

    public function errorPage($errorMsg)
    {
        $smarty = $this->app->page();
        $smarty->value('errorMsg', $errorMsg);
        $smarty->output('mobile/error.tpl');
    }
}
